
package com.be.beadmin.product.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.basicData.repository.UserRepository;
import com.be.beadmin.basicData.service.UserService;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.design.entity.ProductDrawingInfo;
import com.be.beadmin.design.mapper.StandFileInfoMapper;
import com.be.beadmin.design.repository.BopInfoRepository;
import com.be.beadmin.design.repository.ProductBomOverviewRepository;
import com.be.beadmin.design.repository.ProductDrawingInfoRepository;

import com.be.beadmin.design.repository.StandFileInfoRepository;
import com.be.beadmin.design.service.StandFileInfoService;
import com.be.beadmin.product.dto.input.WorkOrderAndProduct;
import com.be.beadmin.product.dto.input.WorkOrderInforDto;
import com.be.beadmin.product.dto.output.*;
import com.be.beadmin.product.entity.ProductManufactInfor;
import com.be.beadmin.product.entity.ProductManufactInfor_;
import com.be.beadmin.product.entity.WorkOrderInfor;
import com.be.beadmin.product.entity.WorkOrderInfor_;
import com.be.beadmin.product.mapper.ProductManufactInforMapperEx;
import com.be.beadmin.product.mapper.WorkOrderInforMapper;
import com.be.beadmin.product.mapper.WorkOrderInforMapperEx;
import com.be.beadmin.product.repository.ProductManufactInforRepository;
import com.be.beadmin.product.repository.WorkOrderInforRepository;
import com.be.beadmin.product.service.ProductManufactInforService;
import com.be.beadmin.product.service.WorkOrderInforService;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.project.entity.*;
import com.be.beadmin.project.repository.*;
import com.be.beadmin.project.service.BatchPlanService;
import com.be.beadmin.project.service.BatchProductService;
import com.be.beadmin.project.service.InfoService;
import com.be.beadmin.service.service.SerialNumberService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @description 服务实现
 * @date 2023-03-30
 **/
@Service
@RequiredArgsConstructor
public class WorkOrderInforServiceImpl implements WorkOrderInforService {

    @Autowired
    private WorkOrderInforRepository workOrderInforRepository;
    @Autowired
    private WorkOrderInforMapper workOrderInforMapper;
    @Autowired
    private WorkOrderInforMapperEx workOrderInforExMapper;

    @Autowired
    private BatchPlanRepository batchPlanRepository;
    @Autowired
    private BatchPlanService batchPlanService;
    @Autowired
    private BatchProductRepository batchProductRepository;
    @Autowired
    private BatchProductService batchProductService;

    @Autowired
    private InfoRepository infoRepository;

    @Autowired
    private TeamInfoRepository teamInfoRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MasterPlanRepository masterPlanRepository;
    @Autowired
    private SerialNumberService serialNumberService;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private ProductBomOverviewRepository productBomOverviewRepository;
    @Autowired
    private ProductDrawingInfoRepository productDrawingInfoRepository;
    @Autowired
    private BopInfoRepository bopInfoRepository;
    @Autowired
    private ProductManufactInforRepository productManufactInforRepository;

    @Autowired
    private ProductManufactInforMapperEx productManufactInforMapperEx;
    @Autowired
    private ProductManufactInforService productManufactInforService;


    @Autowired
    private UserService userService;

    @Autowired
    private InfoService infoService;

    @Autowired
    private StandFileInfoRepository standFileInfoRepository;

    @Autowired
    private StandFileInfoMapper standFileInfoMapper;
    @Autowired
    private StandFileInfoService standFileInfoService;

//    @Autowired
//    private ProductQualityService productQualityService;


//    @Autowired
//    private  infoRepository;

    /**
     * 最基础的分页查询
     * @param request
     * @param pageEntity
     * @return
     */
    @Override
    public Page<WorkOrderInforEx> getWorkOrderInforObjectByPage(HttpServletRequest request, PageEntity pageEntity) {
//        userService.get
//        UserEx userEx = userService.viewBaseInfo(request);

        // 获取当前用户下的所有项目
        List<String> infoIds = infoService.getInfoIdByCurrentUser(request);
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<WorkOrderInfor> page = workOrderInforRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
//                    boolean isAdmin = false;
//                    for (Role role : userService.getRolesByCurrentUser(request)) {
//                        if (role.getCode().equals("ROLE_Admin")) {
//                            isAdmin = true;
//                        }
//                    }
            List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(WorkOrderInfor_.delete), 0); //过滤为0
                    list.add(pre2);
                    // 如果是系统管理员，所有的都可以看
                    if (!userService.isAdmin(request)) {
                        // 指定项目的工单
                        Path<String> path = root.get(WorkOrderInfor_.infoId);
                        CriteriaBuilder.In<String> in = criteriaBuilder.in(path);
                        for (String infoid : infoIds) in.value(infoid);
                        list.add(criteriaBuilder.and(in));
                    }
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(WorkOrderInfor_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
//        Page<WorkOrderInforEx> page1 = page.map(workOrderInforExMapper::toEntity);
        Page<WorkOrderInforEx> page2 = page.map(new Function<WorkOrderInfor, WorkOrderInforEx>() {
            @Override
            public WorkOrderInforEx apply(WorkOrderInfor workOrderInfor) {
//                    System.out.println(workOrderInforEx.toString());
                BatchProduct product = batchProductRepository.findBatchProductByIdAndDelete(workOrderInfor.getBatchProductId(), 0);

                if (product == null) {
                    workOrderInfor.setDelete(1);
                    workOrderInforRepository.save(workOrderInfor);
                    return null;
                }
                // 需要获取到工单的状态和预警状态
                // 状态--- 根据所有工序的开始和结束状态检查。
                workOrderInfor = updateWorkOrderInforState(workOrderInfor);


                WorkOrderInforEx workOrderInforEx = workOrderInforExMapper.toEntity(workOrderInfor);
                // 工单的计划开始和结束时间以及交付时间都设置为批次计划的时间
                BatchPlan plan = batchPlanRepository.findBatchPlanByIdAndDelete(workOrderInfor.getBatchPlanId(), 0);
//                if (plan==null) {
//                    return null;
//                }
                if (plan == null) {
                    workOrderInforEx.setPlanManufactStartDate(null);
                    workOrderInforEx.setPlanManufactEndDate(null);
//                    workOrderInforEx.setBatchPlanId(null);
//                    workOrderInforEx.setBatchPlanCode(null);
//                    workOrderInforEx.setBatchDeliveryDate(null);
                } else {
                    PlanStage stage = batchPlanService.getStageByBatchPlanAndStageName(plan, "生产装配");
                    workOrderInforEx.setPlanManufactStartDate(stage.getStagePlanStartTime());
                    workOrderInforEx.setPlanManufactEndDate(stage.getStagePlanEndTime());
//                    workOrderInforEx.setBatchPlanId(plan.getId());
//                    workOrderInforEx.setBatchPlanCode(plan.getBatchPlanCode());
//                    workOrderInforEx.setBatchDeliveryDate(plan.getBatchDeliveryDate());
                }

                workOrderInforEx.setBatchProductCode(product.getProductCode());



                return workOrderInforEx;
            }
        });

        return page2;

    }

    private WorkOrderInfor updateWorkOrderInforState(WorkOrderInfor workOrderInfor) {
        String batchProductId = workOrderInfor.getBatchProductId();
        int count = productManufactInforRepository.countProductManufactInforsByBatchProductIdAndDelete(batchProductId,0);
        int unStartedCount = productManufactInforRepository.countProductManufactInforsByBatchProductIdAndProcessStatusAndDelete(batchProductId,0, 0);
        int EndedCount = productManufactInforRepository.countProductManufactInforsByBatchProductIdAndProcessStatusAndDelete(batchProductId,3, 0);

        if (unStartedCount == count ) { // 所有的工序都未开始
            workOrderInfor.setState(0);
        } else if (EndedCount == count){ // 所有的工序都已结束
            workOrderInfor.setState(2);
        } else {    // 其他状态
            workOrderInfor.setState(1);
        }

        workOrderInfor.setAlertStatus(workOrderInfor.getState());
        // 设置预警状态 --- 所有工序只要有未按计划时间开始就设置未按计划时间状态，所有工序只要有未按计划时间结束也设置预警状态，
        int unPlanStartCount = productManufactInforRepository.countProductManufactInforsByBatchProductIdAndAlertStatusAndDelete(batchProductId,4, 0);
        int unPlanEndCount = productManufactInforRepository.countProductManufactInforsByBatchProductIdAndAlertStatusAndDelete(batchProductId,5, 0);

        if (unPlanStartCount > 0) {
            workOrderInfor.setAlertStatus(3);
        }
        if (unPlanEndCount > 0) {
            workOrderInfor.setAlertStatus(4);
        }
        WorkOrderInfor save = workOrderInforRepository.save(workOrderInfor);

        return save;

    }

    @Override
    public Page<WorkOrderInforEx> getWorkOrderInforByPage(HttpServletRequest request,PageEntity pageEntity) {
        List<String> infoIds = infoService.getInfoIdByCurrentUser(request);

        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<WorkOrderInfor> page = workOrderInforRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {


            List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(WorkOrderInfor_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(WorkOrderInfor_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<WorkOrderInforEx> page1 = page.map(workOrderInforExMapper::toEntity);

        return page1;

    }

    /**
     * 根据id获取工单
     *
     * @param id
     * @return
     */
    @Override
    public WorkOrderInfor getWorkOrderInforById(String id) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforByIdAndDelete(id, 0);
        if (workOrderInfor == null) {
            throw new BeadminException("未找到工单");
        }
        return workOrderInfor;
    }

    @Override
    public Page<WorkOrderInforEx> getWorkOrderInforReleasedByPage(HttpServletRequest request ,PageEntity pageEntity) {
        List<String> infoIds = infoService.getInfoIdByCurrentUser(request);

        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() - 1,
                pageEntity.getPageSize());
        Page<WorkOrderInfor> page = workOrderInforRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
//                    boolean isAdmin = false;
//                    for (Role role : userService.getRolesByCurrentUser(request)) {
//                        if (role.getCode().equals("ROLE_Admin")) {
//                            isAdmin = true;
//                        }
//                    }
            List<Predicate> list = new ArrayList<>();
                    Predicate pre1 = JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(WorkOrderInfor_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(WorkOrderInfor_.releaseFlag), 1); //过滤为0
                    list.add(pre3);
                    if (!userService.isAdmin(request)) {
                        // 指定项目的工单
                        Path<String> path = root.get(WorkOrderInfor_.infoId);
                        CriteriaBuilder.In<String> in = criteriaBuilder.in(path);
                        for (String infoid : infoIds) in.value(infoid);
                        list.add(criteriaBuilder.and(in));
                    }
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if (pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(WorkOrderInfor_.createTime).as(Date.class)));
                    }
                    return criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<WorkOrderInforEx> page1 = page.map(workOrderInforExMapper::toEntity);

        return page1;

    }

    @Override
    public void addWorkOrderInfor(WorkOrderInforDto workOrderInforDto) {
        WorkOrderInfor result = workOrderInforRepository.findWorkOrderInforByIdAndDelete(workOrderInforDto.getId(), 0);
        if (ObjectUtil.isNotEmpty(result)) {
            throw new BeadminException("WorkOrderInfor不存在,请重新查询");
        }
        WorkOrderInfor workOrderInfor = workOrderInforMapper.toEntity(workOrderInforDto);
        workOrderInforRepository.save(workOrderInfor);
    }

    @Override
    public void updateWorkOrderInfor(WorkOrderInforDto workOrderInforDto) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforById(workOrderInforDto.getId());
        workOrderInfor = workOrderInforMapper.toEntity(workOrderInforDto);
        workOrderInforRepository.save(workOrderInfor);
    }


    @Override
    public void delWorkOrderInfor(String id) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforById(id);
        workOrderInfor.setDelete(1);
        workOrderInforRepository.save(workOrderInfor);
    }

    @Override
    public void delWorkOrderInfors(List<String> ids) {
    }





    /**
     * 获取工单的图纸信息
     *
     * @param workOrderInfoId
     * @return
     */
    @Override
    public List<ProductDrawingInfo> getDrawingInfo(String workOrderInfoId) {
        String batchProductId = workOrderInforRepository.findBatchProductIdByWorkOrderInforIdAndDelete(workOrderInfoId, 0);
//        System.out.println("batchProductId"+batchProductId);
        BatchProduct batchProduct = batchProductRepository.findBatchProductByIdAndDelete(batchProductId, 0);
//        System.out.println("batchProduct"+batchProduct);
        List<ProductDrawingInfo> productDrawingInfos = productDrawingInfoRepository.findProductDrawingInfosByProductCodeAndDelete(batchProduct.getProductCode(), 0);
//        System.out.println("productDrawingInfos"+productDrawingInfos);

        return productDrawingInfos;
    }

    /**
     * 获取工单的生产进度信息
     *
     * @param workOrderInfoId
     * @return
     */
    @Override
    public List<ProductManufactInforEx> getManufactInfo(String workOrderInfoId) {
        String batchProductId = workOrderInforRepository.findBatchProductIdByWorkOrderInforIdAndDelete(workOrderInfoId, 0);
        if (Objects.equals(batchProductId, "")) throw new BeadminException("未找到该工单的柜体");
//        System.out.println("batchProductId"+batchProductId);
        BatchProduct batchProduct = batchProductRepository.findBatchProductByIdAndDelete(batchProductId, 0);
//        System.out.println("batchProduct"+batchProduct);
        List<ProductManufactInfor> productManufactInfors = productManufactInforRepository.findProductManufactInforsByBatchProductCodeAndDeleteOrderBySequenceAsc(batchProduct.getProductCode(), 0);
//        System.out.println("productDrawingInfos"+productDrawingInfos);
        productManufactInfors.forEach(productType -> productType.setProductType(batchProduct.getProductType()) );

        return productManufactInforMapperEx.toEntity(productManufactInfors) ;
//        return null;
    }

    /**
     * 分页的查询接口扩展
     *
     * @param pageEntity
     * @return
     */
    @Override
    public Object getWorkOrderInforExtendByPage(HttpServletRequest request ,PageEntity pageEntity) {
        Page<WorkOrderInforEx> workOrderInforExPage = getWorkOrderInforObjectByPage(request,pageEntity);
//        Streamable<WorkOrderInforEx> filter = workOrderInforExPage.filter(new java.util.function.Predicate<WorkOrderInforEx>() {
//            @Override
//            public boolean test(WorkOrderInforEx workOrderInforEx) {
//                return workOrderInforEx != null;
//            }
//        });
        Object o = workOrderInforExPage.map(new Function<WorkOrderInforEx, Object>() {
            @Override
            public Object apply(WorkOrderInforEx workOrderInforEx) {
//                if (workOrderInforEx == null ) return null;
                WorkOrderInforQueryEx workOrderInforQueryEx = new WorkOrderInforQueryEx();
                List<ProductManufactInfor> productManufactInfors = productManufactInforRepository.findProductManufactInforsByBatchProductIdAndDelete(workOrderInforEx.getBatchProductId(), 0);
                List<ProductManufactInforStatusEx> productManufactInforStatusExes = new ArrayList<>();
                productManufactInfors.forEach(productManufactInfor -> {
                    ProductManufactInforStatusEx productManufactInforStatusEx = new ProductManufactInforStatusEx();
                    productManufactInforStatusEx.setId(productManufactInfor.getId());
                    productManufactInforStatusEx.setProcessName(productManufactInfor.getProcessName());
                    productManufactInforStatusEx.setAlertStatus(productManufactInfor.getAlertStatus());
                    productManufactInforStatusExes.add(productManufactInforStatusEx);
                });
                workOrderInforQueryEx.setWorkOrderInforEx(workOrderInforEx);
                workOrderInforQueryEx.setChildren(productManufactInforStatusExes);
                return workOrderInforQueryEx;
            }
        });
        return o;
    }
    /**
     * 工单对应的项目团队经理
     *
     * @param workOrderInfoId
     * @return
     */
    @Override
    public User getTeamManager(String workOrderInfoId) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforById(workOrderInfoId);
        String infoId = workOrderInfor.getInfoId();
        Info info = infoRepository.findInfoById(infoId);
        String teamId = info.getTeamId();
        TeamInfo teamInfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(teamId, "项目经理", 0);
        if (teamInfo == null) {
            User user = null;
            return user;
        }
        User user = userRepository.findUserByIdAndDelete(teamInfo.getUserId(), 0);
        return user;
    }

    @Override
    public User  getTeamManufactManager(String workOrderInfoId) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforById(workOrderInfoId);
        String infoId = workOrderInfor.getInfoId();
        Info info = infoRepository.findInfoById(infoId);
        String teamId = info.getTeamId();
        TeamInfo teamInfo = teamInfoRepository.findTeamInfoByTeamIdAndCategoryAndDelete(teamId,"生产经理", 0);
        if(teamInfo==null) throw new BeadminException("项目团队缺少生产经理");
        else{
            return userRepository.findUserByIdAndDelete(teamInfo.getUserId(), 0);
        }
    }

    /**
     * 根据工单设置工单排程状态
     *
     * @param workOrderInfor
     * @param scheduledFlag
     */
    @Override
    public void setWorkOrderScheduledFlag(WorkOrderInfor workOrderInfor, int scheduledFlag) {
        workOrderInfor.setScheduledFlag(scheduledFlag);
        workOrderInforRepository.save(workOrderInfor);
    }

    /**
     * 根据柜体设置工单排程状态
     *
     * @param batchProduct
     * @param scheduledFlag
     */
    @Override
    public void setWorkOrderScheduledFlag(BatchProduct batchProduct, int scheduledFlag) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforByBatchProductIdAndDelete(batchProduct.getId(), 0);
        setWorkOrderScheduledFlag(workOrderInfor, scheduledFlag);
    }

    /**
     * 根据批次计划ID获取工单列表
     *
     * @param batchPlanId
     * @return
     */
    @Override
    public List<WorkOrderInforByBpEx> getWorkOrderInforByBatchPlanId(String batchPlanId) {
//        BatchPlan batchPlanById = batchPlanService.getBatchPlanById(batchPlanId);
        List<String> stringList = batchProductRepository.getBatchProductIdsByBatchPlanIdAndDelete(batchPlanId, 0);

        return getWorkOrderInforByProductIds(stringList,null);

    }

    private List<WorkOrderInforByBpEx> getWorkOrderInforByProductIds(List<String> stringList, Boolean scheduleFlag) {

        List<WorkOrderInforByBpEx> workOrderInforByBpExes = new ArrayList<>();
        List<WorkOrderInfor> workOrderInfors = new ArrayList<>();
        if (scheduleFlag == null ){
            workOrderInfors = workOrderInforRepository.findWorkOrderInforsByBatchProductIdInAndDelete(stringList, 0);
        } else if (scheduleFlag) { // 已排程的工单
            workOrderInfors = workOrderInforRepository.findWorkOrderInforsByBatchProductIdInAndScheduledFlagNotAndDelete(stringList, 0,0);
        } else {    // 未排程的工单
            workOrderInfors = workOrderInforRepository.findWorkOrderInforsByBatchProductIdInAndScheduledFlagAndDelete(stringList,0, 0);
        }

        for (WorkOrderInfor workOrderInfor : workOrderInfors) {
            BatchProduct batchProduct = batchProductRepository.findBatchProductByIdAndDelete(workOrderInfor.getBatchProductId(),0);


            WorkOrderInforByBpEx workOrderInforByBpEx = new WorkOrderInforByBpEx(
                    workOrderInfor.getId(),
                    workOrderInfor.getProjectName(),
                    workOrderInfor.getProjectCode(),
                    workOrderInfor.getBatchPlanCode(),
                    workOrderInfor.getBatchProductCode(),
                    workOrderInfor.getWo(),
                    batchProduct.getBatchDeliveryDate()
            );
            workOrderInforByBpExes.add(workOrderInforByBpEx);

        }
        return workOrderInforByBpExes;


    }

    /**
     * 根据批次计划ID获取已排程工单列表
     *
     * @param batchPlanId
     * @return
     */
    @Override
    public List<WorkOrderInforByBpEx> getWorkOrderInforByBatchPlanIdAndScheduled(String batchPlanId) {
        List<String> stringList = batchProductRepository.getBatchProductIdsByBatchPlanIdAndDelete(batchPlanId, 0);
        return getWorkOrderInforByProductIds(stringList,true);
    }

    /**
     * 根据批次计划ID获取未排程工单列表
     *
     * @param batchPlanId
     * @return
     */
    @Override
    public List<WorkOrderInforByBpEx> getWorkOrderInforByBatchPlanIdAndUnscheduled(String batchPlanId) {
        List<String> stringList = batchProductRepository.getBatchProductIdsByBatchPlanIdAndDelete(batchPlanId, 0);
        return getWorkOrderInforByProductIds(stringList,false);
    }

    @Override
    public WorkOrderInfor getWorkOrderInforByWo(String wo) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforByWo(wo);
        return workOrderInfor;
    }

    /**
     * 删除所有工单
     *
     * @param id
     */
    @Override
    public void deleteWoByInfo(String id) {
        workOrderInforRepository.deleteWorkOrderInforByInfo(1,id);
    }

    @SneakyThrows
    @Override
    public String getDrawingPreviewUrl(String productDrawingInfoId) {
        ProductDrawingInfo productDrawingInfo = productDrawingInfoRepository.findProductDrawingInfoByIdAndDelete(productDrawingInfoId, 0);
        if (productDrawingInfo == null) {
            throw new BeadminException("请检查该图纸是否存在");
        }
        String fileCode = productDrawingInfo.getDrawingCode();
//        // 获取到指定的标准图纸文件
//        StandFileInfo standFileInfo = standFileInfoRepository.findStandFileInfoByFileCodeAndDelete(fileCode, 0);
//        StandFileInfoDto standFileInfoDto = standFileInfoMapper.toDto(standFileInfo);
        // 获取到最新的路径， 并保存
        String previewUrl = minioUtil.getPreviewFileUrl("standfile",fileCode+"+1+"+productDrawingInfo.getDrawingName());
        // 路径设置为最新的
        productDrawingInfo.setDrawingUrl(previewUrl);
        productDrawingInfoRepository.save(productDrawingInfo);

        return previewUrl;
    }

    @Override
    public List<String> getWos(String s) {
//        List<WorkOrderInfor> workOrderInfors = workOrderInforRepository.findWorkOrderInforsByDelete(0);
//        List<String> wos = workOrderInfors.stream().map(WorkOrderInfor::getWo).collect(Collectors.toList());
        List<String> wos = workOrderInforRepository.findWosBySpecifiedCondition(s);
        return wos;
    }


    @Override
    public ArrayList<Integer> getWorkOrderInforProgress() {
        Integer workOrderInforNumber = workOrderInforRepository.countWorkOrderInforByDelete(0);
        Integer unstartedWorkOrderInforNumber = workOrderInforRepository.countWorkOrderInforByStateAndDelete(0,0);
        Integer startedWorkOrderInforNumber = workOrderInforNumber - unstartedWorkOrderInforNumber;
        Integer offScheduleStartWorkOrderInforNumber = workOrderInforRepository.countWorkOrderInforByAlertStatusAndDelete(3,0);
        Integer offScheduleFinishWorkOrderInforNumber = workOrderInforRepository.countWorkOrderInforByAlertStatusAndDelete(4,0);
        Integer plannedWorkOrderInforNumber = workOrderInforNumber - offScheduleStartWorkOrderInforNumber - offScheduleFinishWorkOrderInforNumber;
        ArrayList<Integer> workOrderInforProgress = new ArrayList<>();
        workOrderInforProgress.add(0,workOrderInforNumber);
        workOrderInforProgress.add(1,unstartedWorkOrderInforNumber);
        workOrderInforProgress.add(2,startedWorkOrderInforNumber);
        workOrderInforProgress.add(3,plannedWorkOrderInforNumber);
        workOrderInforProgress.add(4,offScheduleStartWorkOrderInforNumber);
        workOrderInforProgress.add(5,offScheduleFinishWorkOrderInforNumber);
        return workOrderInforProgress;
    }

    @Override
    public List<Integer> countYearMonthWorkOrderInforByDate(Integer month, Integer year) {
        List<Integer> list = new ArrayList<>();
        Integer monthRes = workOrderInforRepository.countYearMonthWorkOrderInforByStateAndCloseTimeAndDelete(month,year);
        Integer yearRes = workOrderInforRepository.countYearMonthWorkOrderInforByStateAndCloseTimeAndDelete(null, year);
        list.add(0, monthRes);
        list.add(1,yearRes);
        return list;
     }

    @Override
    public List<String> getWoListByProjectCode(String projectCode) {
        List<WorkOrderInfor> workOrderInforList = workOrderInforRepository.findWorkOrderInforsByProjectCodeAndDelete(projectCode , 0);
        List<String> woList = workOrderInforList.stream().map(workOrderInfor -> workOrderInfor.getWo()).collect(Collectors.toList());
        return woList;
    }

    @Override
    public List<User> getTeamMember(String workOrderInfoId) {
        WorkOrderInfor workOrderInfor = workOrderInforRepository.findWorkOrderInforById(workOrderInfoId);
        String infoId = workOrderInfor.getInfoId();
        Info info = infoRepository.findInfoById(infoId);
        String teamId = info.getTeamId();
        List<TeamInfo> teamInfoList = teamInfoRepository.findTeamInfosByTeamIdAndDelete(teamId, 0);
        List<User> userList = new ArrayList<>();
        Set<String>userIdSet = new LinkedHashSet<>();
        for (TeamInfo teamInfo : teamInfoList) {
            String userId=teamInfo.getUserId();
            if(userIdSet.add(userId)) {
                User user = userRepository.findUserByIdAndDelete(userId, 0);
                userList.add(user);
            }

        }
        return userList;
    }

    @Override
    public List<WorkOrderInfor> getWorkOrderInforList() {
        List<WorkOrderInfor> workOrderInforList = workOrderInforRepository.findWorkOrderInforsByDelete(0);
        return workOrderInforList;
    }

    @Override
    public List<WorkOrderInfor> getWorkOrderInforListByInfoId(String infoId) {
        List<WorkOrderInfor> workOrderInforList = workOrderInforRepository.findWorkOrderInforsByInfoIdAndDelete(infoId,0);
        return workOrderInforList;
    }

    /**
     * 获取所有工单和柜体别名对应信息
     *
     * @return
     */
    @Override
    public List<WorkOrderAndProduct> getWorkOrderInforAndproductName() {
        List<WorkOrderAndProduct> workOrderAndProducts = new ArrayList<>();
        for (WorkOrderInfor workOrderInfor : workOrderInforRepository.findWorkOrderInforsByDelete(0)) {
            WorkOrderAndProduct workOrderAndProduct = new WorkOrderAndProduct();
            BatchProduct batchProduct = batchProductRepository.findBatchProductByIdAndDelete(workOrderInfor.getBatchProductId(), 0);
            workOrderAndProduct.setWorkOrderId(workOrderInfor.getId());
            workOrderAndProduct.setWorkOrderCode(workOrderInfor.getWo());
            workOrderAndProduct.setProductName(batchProduct.getProductCode());
            workOrderAndProducts.add(workOrderAndProduct);
        }

        return workOrderAndProducts;
    }

    /*cx补充代码*可删：代码功能补充生产看板超期预警查询**/
    @Override
    public List<WorkOrderInfor> getWorkOrderInforExtendWarnByPage() {
        List<WorkOrderInfor> warnlist = workOrderInforRepository.findWorkOrderInforsByAlertStatusAndDelete(4,0);
        return warnlist;
    }

}